package org.qqcui.designpattern.patterns.interpreter;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 解释器模式客户端
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022/5/7 11:17
 **/
public class Client {

    public static void main(String[] args) throws IOException {
        // 获取计算表达式
        String expr = getExpr();

        Map<String, Integer> var =getValue(expr);

        Calculator calculator = new Calculator(expr);
        System.out.println("运算结果：" + expr + "=" + calculator.run(var));
    }

    /**
     * 解析表达式
     * @param expr
     * @return
     */
    private static Map<String, Integer> getValue(String expr) throws IOException {
        Map<String, Integer> map = new HashMap<>();
        char[] chars = expr.toCharArray();
        for (char c : chars) {
            if ('+' != c && '-' != c) {
                if (!map.containsKey(String.valueOf(c))) {
                    System.out.println("请输入" + String.valueOf(c) + "的值：");
                    String in = new BufferedReader(new InputStreamReader(System.in)).readLine();
                    map.put(String.valueOf(c), Integer.valueOf(in));
                }
            }
        }
        return map;
    }

    /**
     * 获取输入表达式
     * @return
     * @throws IOException
     */
    public static String getExpr() throws IOException {
        System.out.println("请输入表达式：");
        return new BufferedReader(new InputStreamReader(System.in)).readLine();
    }
}
